package org.wso2.carbon.registry.lifecycle.accenture.sample.executors;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.governance.registry.extensions.interfaces.Execution;
import org.wso2.carbon.registry.core.Comment;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.jdbc.handlers.RequestContext;
import org.wso2.carbon.registry.lifecycle.accenture.sample.utils.NotificationUtil;

import java.util.Map;
import java.util.Set;

public class CommentExecutor implements Execution {

    private Map parameterMap;
    private static final Log log = LogFactory.getLog(CommentExecutor.class);
    public void init(Map map) {
        parameterMap = map;
    }

    public boolean execute(RequestContext requestContext, String currentState, String targetState) {

        String resourcePath = requestContext.getResource().getPath();
        Resource resource = requestContext.getResource();
        Registry registry =  requestContext.getRegistry();

        String commentValue = "";

        Set parameterMapKeySet = (Set) requestContext.getProperty("parameterNames");
        if (parameterMapKeySet == null) {
            return false;
        }
        for (Object entry : parameterMapKeySet) {
            String key = (String) entry;
            if (key.equals("comments")) {
                commentValue = (String) requestContext.getProperty(key);
                break;
            }
        }
        try {
            String resourceVersions[] = registry.getVersions(resourcePath);
            Comment comment = new Comment();
            String backEndUrl = NotificationUtil.getBackendServerUrl();
            String msg = backEndUrl+"carbon/resources/resource.jsp?viewType=std&path="+resourceVersions[0];
            comment.setText("<a href='"+msg+"'>"+
                    resourceVersions[0].substring(resourceVersions[0].lastIndexOf("/"))+"</a>" +"\n" + commentValue);
            String commentPath = registry.addComment(resourcePath, comment);
            if (commentPath == null) {
                log.error("Failed to add comment" + resourceVersions[0] + " ;" + commentValue);
            }
            return true;
        } catch (RegistryException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            return false;
        }

    }
}
